import cv2
import dlib

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

src_img = cv2.imread("src.jpg")
dst_img = cv2.imread("dst.jpg")

src_faces = detector(src_img)
dst_faces = detector(dst_img)

if len(src_faces) > 0 and len(dst_faces) > 0:

    src_landmarks = predictor(src_img, src_faces[0])
    dst_landmarks = predictor(dst_img, dst_faces[0])

    src_points = []
    dst_points = []
    for i in range(68):
        src_points.append((src_landmarks.part(i).x, src_landmarks.part(i).y))
        dst_points.append((dst_landmarks.part(i).x, dst_landmarks.part(i).y))

    src_points = np.array(src_points, dtype=np.float32)
    dst_points = np.array(dst_points, dtype=np.float32)

    affine_matrix = cv2.getAffineTransform(src_points[:3], dst_points[:3])
    warped_src = cv2.warpAffine(src_img, affine_matrix, (dst_img.shape[1], dst_img.shape[0]))

    mask = np.zeros(dst_img.shape, dtype=np.uint8)
    cv2.fillConvexPoly(mask, dst_points.astype(np.int32), (255, 255, 255))
    dst_face = cv2.bitwise_and(dst_img, mask)
    warped_face = cv2.bitwise_and(warped_src, cv2.bitwise_not(mask))
    result = cv2.add(dst_face, warped_face)

    cv2.imshow("Result", result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
else:
    print("未检测到人脸")